package mybatis.service.impl;


import mybatis.dao.CartDao;
import mybatis.dao.GameDao;
import mybatis.entity.Cart;
import mybatis.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;


@Service
public class CartServiceImpl implements CartService {
	@Autowired
	private GameDao gameDao;
	@Autowired
	private CartDao cartDao;
	@Override
	public void add(int gameId, int userId, String count) {

		Cart cart =cartDao.findByUidAndGid(gameId,userId);
		HashMap<String, BigDecimal> map = gameDao.findPrices(gameId);
		if(cart == null) {
			BigDecimal oprice = map.get("oprice").multiply(new BigDecimal(count));
			BigDecimal fprice = map.get("fprice").multiply(new BigDecimal(count));
			cartDao.add(gameId, userId, Integer.parseInt(count), oprice, fprice);
		}else {
			int oldCount = cart.getGamecount();
			int id = cart.getId();
			System.out.println(cart.getOldprice());
			BigDecimal oprice = cart.getOldprice().add(map.get("oprice").multiply(new BigDecimal(count)));
			BigDecimal fprice = cart.getFinalprice().add(map.get("fprice").multiply(new BigDecimal(count)));
			cartDao.changeCount(id, Integer.parseInt(count)+oldCount,oprice,fprice);

		}
		
	}
	//获取用户所有购物车商品
	@Override
	public List<Cart> findByUid(int userId) {
		List<Cart> list = cartDao.findByUid(userId);
		// TODO Auto-generated method stub
		return list;
	}
	//根据游戏id和用户id查找购物车

	//删除游戏
	@Override
	public void deleteByGid(int gameId, int userId) {

		// TODO Auto-generated method stub
		
	}
	//更改数量
	@Override
	public void changeCount(int Cartid, int gameCount) {

		// TODO Auto-generated method stub
		Cart cart =cartDao .findByCid(Cartid);
		BigDecimal oprice = cart.getGame().getGame_original_price().multiply(new BigDecimal(gameCount));
		BigDecimal fprice = cart.getGame().getGame_final_price().multiply(new BigDecimal(gameCount));
		cartDao.changeCount(Cartid, gameCount, oprice, fprice);

	}
	@Override
	public Cart findByCid(int Cartid) {

		// TODO Auto-generated method stub
		Cart cart =cartDao .findByCid(Cartid);
		return cart;		
	};
}
